<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom:10px">
      <!-- <el-input v-model="listQuery.name" placeholder="品名" style="width: 100px;margin-bottom:3px" class="filter-item" @keyup.enter.native="handleFilter" /> -->
      <el-select v-model="listQuery.name" placeholder="品名" clearable style="width: 90px;margin-bottom:3px" class="filter-item" filterable>
        <el-option v-for="item in selectItems.goods" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.number" placeholder="品号" clearable style="width: 90px;margin-bottom:3px" class="filter-item" :disabled="!listQuery.name" filterable>
        <el-option v-for="item in selectItems.goodsNumber[listQuery.name]" :key="item.code" :label="item.code" :value="item.code"/>
      </el-select>
      <el-select v-model="listQuery.company" placeholder="客户" clearable style="width: 90px;margin-bottom:3px" class="filter-item" filterable>
        <el-option v-for="item in selectItems.companies" :key="item" :label="item" :value="item"/>
      </el-select>
      <el-select v-model="listQuery.warehouse" placeholder="仓库" clearable style="width: 90px;margin-bottom:3px" class="filter-item" filterable>
        <el-option v-for="item in selectItems.warehouse" :key="item" :label="item" :value="item" />
      </el-select>
      <!-- <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px;margin-bottom:3px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select> -->
      <el-date-picker v-model="listQuery.datestart" type="date" placeholder="开始时间" />
      <el-date-picker v-model="listQuery.dateend" type="date" placeholder="截止时间" />
      <br/>
      <br/>

      <el-button v-waves class="filter-item" style="margin-bottom:3px" type="primary" icon="el-icon-search" size='mini' @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-bottom:3px" type="primary" icon="el-icon-edit" size='mini' @click="handleCreate">
        新建加工单
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" style="margin-bottom:3px" type="primary" icon="el-icon-download" size='mini' @click="handleDownload">
        导出excel
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      ref="singleTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @current-change="handleCurrentChange"
    >

      <!-- <el-table-column label="销售单号" align="center" width="140">
        <template slot-scope="{row}">
          <span>{{ row.saleCode }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="产品名称" prop="name" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="品号" min-width="100px">
        <template slot-scope="{row}">
            {{ row.number }} 
        </template>
      </el-table-column>

      <el-table-column label="加工企业" min-width="100px">
        <template slot-scope="{row}">
            {{ row.company }} 
        </template>
      </el-table-column>

      <el-table-column label="发出匹数" min-width="100px">
        <template slot-scope="{row}">
            {{ row.outPiece }} 
        </template>
      </el-table-column>

      <el-table-column label="发出米数" min-width="100px">
        <template slot-scope="{row}">
            {{ row.outLength }} 
        </template>
      </el-table-column>

      <!-- <el-table-column label="发入匹数" min-width="100px">
        <template slot-scope="{row}">
            {{ row.inPiece }} 
        </template>
      </el-table-column>

      <el-table-column label="发入米数" min-width="100px">
        <template slot-scope="{row}">
            {{ row.inLength }} 
        </template>
      </el-table-column>

      <el-table-column label="缩率（平均）" min-width="100px">
        <template slot-scope="{row}">
            {{ row.balance | balanceFilter}} 
        </template>
      </el-table-column> -->

      <el-table-column label="发出仓库" min-width="100px">
        <template slot-scope="{row}">
            {{ row.warehouse }} 
        </template>
      </el-table-column>

      <!-- <el-table-column label="退回仓库" min-width="100px">
        <template slot-scope="{row}">
            {{ row.inWarehouse }} 
        </template>
      </el-table-column> -->

      <el-table-column label="加工日期" min-width="110px" sortable="custom" prop="date">
        <template slot-scope="{row}">
            {{ row.date }} 
        </template>
      </el-table-column>

      <el-table-column label="填写人员" min-width="100px">
        <template slot-scope="{row}">
            {{ row.operator }} 
        </template>
      </el-table-column>

      <el-table-column label="备注" min-width="100px">
        <template slot-scope="{row}">
            {{ row.remark }} 
        </template>
      </el-table-column>
 
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width" style="margin-left:0px">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)" :disabled="permission(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)" style="margin-left:0px" :disabled="permission(row)">
            删除
          </el-button>
          
        </template>
      </el-table-column>
    </el-table>

    <pagination v-if="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :lock-scroll="false" :append-to-body="true" >
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        
        <el-form-item label="品名" prop="name" >
          <el-select v-model="temp.name" class="filter-item" placeholder="请选择品名" filterable>
            <el-option v-for="item in selectItems.goods" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="品号" prop="number" >
          <el-select v-model="temp.number" class="filter-item" placeholder="请选择品号" :disabled="temp.name.length==0" filterable>
            <el-option v-for="item in selectItems.goodsNumber[temp.name]" :key="item.code" :label="item.code" :value="item.code" />
          </el-select>
        </el-form-item>

        <el-form-item label="加工企业" prop="company">
          <el-select v-model="temp.company" class="filter-item" placeholder="请选择加工企业" filterable>
            <el-option v-for="item in selectItems.companies" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="发出匹数" prop="outPiece">
          <el-input v-model="temp.outPiece" type="number" @mousewheel.native.prevent/>
        </el-form-item>

        <el-form-item label="发出米数" prop="outLength">
          <el-input v-model="temp.outLength" type="number" @mousewheel.native.prevent/>
        </el-form-item>

        <!-- <el-form-item label="发入匹数" prop="outPiece">
          <el-input v-model="temp.inPiece" type="number" @mousewheel.native.prevent @input="setBalance"/>
        </el-form-item>

        <el-form-item label="发入米数" prop="outLength">
          <el-input v-model="temp.inLength" type="number" @mousewheel.native.prevent @input="setBalance"/>
        </el-form-item>

        <el-form-item label="缩率" prop="outLength">
          <el-input v-model="temp.balance" type="number" @mousewheel.native.prevent/>
        </el-form-item> -->

        <el-form-item label="发出仓库" prop="warehouse">
          <el-select v-model="temp.warehouse" class="filter-item" placeholder="请选择仓库" filterable>
            <el-option v-for="item in selectItems.warehouse" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="发入仓库" prop="warehouse">
          <el-select v-model="temp.inWarehouse" class="filter-item" placeholder="请选择仓库" filterable>
            <el-option v-for="item in selectItems.warehouse" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="加工日期" prop="date">
          <el-date-picker v-model="temp.date" type="date" placeholder="请选择日期" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="" />
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="funcMap[dialogStatus]()">
          确认
        </el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import { fetchProcessBillList, createProcessBill, updateProcessBill , deleteProcessBill, fetchSelectItemList} from '@/api/processBill'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

function formatDate(date) {
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? '0' + m : m;
  var d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  return y + '-' + m + '-' + d;
}

export default {
  name: 'ProcessBill',
  components: { Pagination },
  directives: { waves },
  computed:{ user:{
    get(){
      const token = this.$store.getters.token;
      return{
        name:token.name,
        role:token.role
      }
    }
  }},
  filters: {
    balanceFilter(value) {
      return String((value * 100).toFixed(2)) + '%';
    },
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        // name:'',
        // number:'',
        // warehouse:'',
        // date:'',
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      selectItems:{goods:[],goodsNumber:{},warehouse:[],companies:[]},
      showReviewer: false,
      temp: {
        _id:'',
        processCode:'',
        number: '',
        name: '',
        company:'',
        outPiece:0,
        outLength:0,
        inPiece:0,
        inLength:0,
        balance:0,
        warehouse:'',
        inWarehouse:'',
        date:'',
        operator:'',
        remark:'',
        dateFill:'',
      },
        
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        returned: '退货',
        create: '新建',
      },
      funcMap:{
        update:this.updateData,
        create:this.createData,
        returned:this.returnedData,
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '必须选择品名', trigger: 'change' }],
        number: [{ required: true, message: '必须选择品号', trigger: 'change' }],
        warehouse: [{ required: true, message: '必须选择仓库', trigger: 'change' }],
        company: [{ required: true, message: '必须选择加工企业', trigger: 'change' }],
        date: [{ required: true, message: '日期必须填写', trigger: 'change' }],
        piece: [{ required: true, message: '必须填写数量', trigger: 'blur' }],
        length: [{ required: true, message: '必须填写米数', trigger: 'blur' }],
        returnedWarehouse: [{ required: true, message: '必须选择仓库', trigger: 'change' }],
        returnedDate: [{ required: true, message: '日期必须填写', trigger: 'change' }],
        inLength: [{ required: true, message: '退货米数必须填写', trigger: 'change' }],
      },
      downloadLoading: false
    }
  },
  created() {
    this.getItemList();
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchProcessBillList(this.listQuery).then(response => {
        this.list = response.list.map(v=>{
          var date = new Date(v.date);
          v.date = formatDate(date);
          v.dateFill = new Date(v.dateFill);
          return v;
        });
        this.total = response.total;
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 500)
      })
    },
    getItemList(){
      fetchSelectItemList().then(response => {
        this.selectItems.goods = response.goods;
        this.selectItems.goodsNumber = response.goodsNumber;
        this.selectItems.warehouse = response.warehouse;
        this.selectItems.companies = response.companies;
        this.getList();
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'date') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = +1
      } else {
        this.listQuery.sort = -1
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp= {
        _id:'',
        processCode:'',
        number: '',
        name: '',
        company:'',
        outPiece:0,
        outLength:0,
        inPiece:0,
        inLength:0,
        balance:0,
        warehouse:'',
        inWarehouse:'',
        date:'',
        operator:'',
        remark:'',
        dateFill:'',
      }
    },

    setBalance(){
      if(this.temp.inLength != 0 || this.temp.inPiece != 0){
        this.temp.balance = ((this.temp.inLength / this.temp.inPiece) - (this.temp.outLength / this.temp.outPiece)) / (this.temp.inLength / this.temp.inPiece);
      }
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create';
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.date = new Date(this.temp.date);
          this.temp.operator = this.user.name;
          createProcessBill(this.temp).then((res) => {
            if(res.data == undefined){
              alert(`库存不足，剩余${res.leftPiece}匹，${res.leftLength}米！`);
              return;
            }
            this.temp = res.data;
            this.temp.date = formatDate(new Date(this.temp.date));
            this.temp.dateFill = new Date();
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      // console.log(this.temp)
      // this.temp._id = 
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.balance = Number(this.temp.money) - Number(this.temp.price) * Number(this.temp.finishLength);
          const tempData = Object.assign({}, this.temp)
        //   tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateProcessBill(tempData).then((res) => {
            if(res.data == undefined){
              alert(`库存不足，剩余${res.leftPiece}匹，${res.leftLength}米！`);
              return;
            }
            const index = this.list.findIndex(v => v._id === this.temp._id)
            this.temp.dateFill = new Date();
            this.temp.date = formatDate(new Date(this.temp.date));
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
        const tempData = Object.assign({}, row) // copy obj
        deleteProcessBill(tempData).then(() => {
            this.$notify({
                title: 'Success',
                message: '删除成功',
                type: 'success',
                duration: 2000
            })
            this.list.splice(index, 1)
        })
      
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['品名', '品号', '加工企业','发出匹数', '发出米数', '发入匹数', '发入米数','缩率（平均）', '发出仓库', '加工日期', '填写人员', '备注'];
        const filterVal = ['name', 'number', 'company', 'outPiece', 'outLength','inPiece', 'inLength', 'balance', 'warehouse', 'date', 'operator', 'remark'];
        
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '加工单'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          // return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },

    setCurrent(row) {
        this.$refs.singleTable.setCurrentRow(row);
      },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    permission(row){
      if(this.user.role[0] == "管理员") return false;
      else{
        if(this.user.name != row.operator){
          return true;
        }
        else{
          let now = new Date();
          if(now - row.dateFill >1000 * 300){
            return true;
          }
          else{
            return false;
          }
        }
      }
    }
  }
}
</script>
